<template>
  <div class="attr">
    <Category></Category>
    <el-card style="margin: 10px 0" v-if="!flag">
      <el-button
        type="primary"
        icon="Plus"
        :disabled="categoryStore.c3Id ? false : true"
        @click="addAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0" :data="AttrData">
        <el-table-column
          label="序号"
          type="index"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column prop="attrName" label="属性名称"></el-table-column>
        <el-table-column label="属性值名称">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 5px"
              v-for="(item, index) in row.attrValueList"
              :key="item.id"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <!-- row：已有的属性对象 -->
          <template #="{ row, $index }">
            <!-- 修改已有属性的按钮 -->
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              :title="`你确定删除${row.attrName}?`"
              width="200px"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="small"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card style="margin: 10px 0" v-if="flag">
      <!-- 展示添加属性与修改数据的结构 -->
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input
            placeholder="请你输入属性名称"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- <el-input label="属性名称" placeholder="请输入属性的名字"></el-input> -->
      <el-button
        type="primary"
        @click="addAttrValue"
        :disabled="attrParams.attrName ? false : true"
        icon="Plus"
        style="margin: 0 10px"
      >
        添加属性值
      </el-button>
      <el-button type="primary" style="margin: 10px 0" @click="flag = 0">
        取消
      </el-button>
      <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
        <el-table-column
          label="序号"
          type="index"
          width="80px"
          align="center"
        ></el-table-column>
        <el-table-column prop="attrName" label="属性值">
          <template #="{ row, $index }">
            <el-input
              :ref="(vc: any) => (inputArr[$index] = vc)"
              v-if="row.flag"
              @blur="handleBlur(row, $index)"
              v-model="row.valueName"
            ></el-input>
            <div @click="toEdit(row, $index)" v-else="row.flag">
              {{ row.valueName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">
          <!-- row：已有的属性对象 -->
          <template #="{ row, $index }">
            <!-- 修改已有属性的按钮 -->
            <el-button
              type="primary"
              size="small"
              icon="Delete"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
      >
        保存
      </el-button>
      <el-button type="primary" style="margin: 0 10px" @click="cancel">
        取消
      </el-button>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import { useCategoryStore } from '@/store/modules/category'
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr'
import { Attr, AttrResponseData, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
let AttrData = ref<Attr[]>([])
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([])
let attrParams = reactive<Attr>({
  attrName: '', //新增的属性的名字
  attrValueList: [], //新增的属性值数组],
  categoryId: '', //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
})
const flag = ref(0)
const categoryStore = useCategoryStore()
const getAttr = async () => {
  let { c1Id, c2Id, c3Id } = categoryStore
  if (!categoryStore.c3Id) return
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code == 200) {
    AttrData.value = result.data
  }
}
watch(
  () => categoryStore.c3Id,
  () => {
    getAttr()
    // console.log(AttrData.value)
  },
)
const addAttr = () => {
  // 添加前要清空数据
  Object.assign(attrParams, {
    attrName: '',
    categoryId: categoryStore.c3Id,
    attrValueList: [],
    categoryLevel: 3,
  })
  flag.value = 1
  attrParams.categoryId = categoryStore.c3Id
}
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}
const updateAttr = (row: Attr) => {
  flag.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
const deleteAttr = async (id: number) => {
  let result = await reqDeleteAttr(id)
  console.log(result)

  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
const save = async () => {
  attrParams.attrValueList.forEach((item) => {
    if (item.valueName.trim() == '') {
      ElMessage({
        type: 'error',
        message: '属性值不能为空',
      })
      return
    }
  })
  // 添加属性
  // 修改属性
  // 发请求
  let result: any = await reqAddOrUpdateAttr(attrParams)

  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '添加属性成功',
    })
    flag.value = 0
    getAttr()
  }
}
// 处理失去焦点的回调函数
const handleBlur = (row: AttrValue, index: number) => {
  console.log(row)
  // 判断输入的属性值是否为空

  if (row.valueName.trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    console.log('不是结束了吗？')

    return
  }

  // 要判断属性值是否一样
  attrParams.attrValueList.forEach((item) => {
    if (item.valueName == row.valueName && row != item) {
      ElMessage({
        type: 'error',
        message: '属性值不能重复',
      })
      attrParams.attrValueList.splice(index, 1)
      // row.flag = true
      return
    }
  })
  row.flag = false
}
const toEdit = (row: AttrValue, index: number) => {
  // console.log(row,index);
  row.flag = true
  nextTick(() => {
    inputArr.value[index].focus()
  })
}
//取消按钮的回调
const cancel = () => {
  flag.value = 0
}
onBeforeUnmount(() => {
  // 清空数据
  categoryStore.$reset()
})
</script>
<style scope></style>
